package com.webchat.ugc.messaegqueue.consumer.rocketmq;

import com.webchat.common.util.JsonUtil;
import com.webchat.domain.vo.request.mess.ChatMessageRequestVO;
import com.webchat.ugc.messaegqueue.service.PersistentMessageService;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;


/**
 * 消息持久化RocketMQ队列
 *
 */
@Component
@RocketMQMessageListener(consumerGroup = "web_chat", topic = "queue_persistent_message")
public class PersistentMessageRocketMQConsumer implements RocketMQListener<String> {

    @Autowired
    private PersistentMessageService persistentMessageService;

    /**
     * 消息持久化
     * @param message
     */
    @Override
    public void onMessage(String message) {
        System.out.println("Received message: " + message);
        ChatMessageRequestVO data = JsonUtil.fromJson(message, ChatMessageRequestVO.class);
        if (data == null) {
            return;
        }
        boolean result = persistentMessageService.persistent(data);
        // 抛出异常，重新入队
        Assert.isTrue(result, "消息持久化失败");
    }
}